package com.uchedao.seller.ui.car.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.uchedao.seller.R;
import com.uchedao.seller.config.GlobalInfo;
import com.uchedao.seller.module.ResultIntArrayPics;
import com.uchedao.seller.util.Util;
import com.uchedao.seller.widget.BadgeView;
import com.uchedao.seller.widget.stickylistheaders.StickyListHeadersAdapter;

import java.util.ArrayList;

public class PaintSurfaceAdapter extends BaseAdapter implements
		StickyListHeadersAdapter {

	private Context mContext;
	private ResultIntArrayPics[] arrays;
	private LayoutInflater inflater;
	private PaintSurfaceAdapterListener listener;
	private String[] values;
	private boolean[] checkedItems;
	private int index;
	private int resultTvWidth;

	public interface PaintSurfaceAdapterListener {
		/**
		 * 图片添加
		 * 
		 * @param result
		 */
		public void onPhotoAdd(ResultIntArrayPics result);

		/**
		 * 图片修改
		 * 
		 * @param result
		 */
		public void onPhotoEdit(ResultIntArrayPics result);
	}

	public PaintSurfaceAdapter(Context act,
			ResultIntArrayPics[] arrays,
			PaintSurfaceAdapterListener skeletonAdapterListener) {
		inflater = LayoutInflater.from(act);
		this.arrays = arrays;
		mContext = act;
		listener = skeletonAdapterListener;
		values = GlobalInfo.resources
				.getStringArray(R.array.paint_surface_select_values);
		resultTvWidth = Util.sp2px(act, 18) * 13;
	}

	@Override
	public int getCount() {
		return arrays.length;
	}

	@Override
	public Object getItem(int position) {
		return arrays[position];
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	private OnClickListener photoAddListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (listener != null)
				listener.onPhotoAdd((ResultIntArrayPics) v.getTag());

		}
	};

	private OnClickListener resultListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			index = (Integer) v.getTag();
			showAlertMultipleChoiceDialog(arrays[index], multipleChoiceListener);
		}
	};

	/**
	 * 多选监听
	 */
	private DialogInterface.OnMultiChoiceClickListener multipleChoiceListener = new DialogInterface.OnMultiChoiceClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which, boolean isChecked) {

			ListView listView = ((AlertDialog) dialog).getListView();

			// 取消选择
			if (!isChecked) {
				// 当选中的数量小于1时
				if (listView.getCheckedItemCount() == 0) {
					listView.setItemChecked(which, true);
					checkedItems[which] = true;
					Toast.makeText(mContext, R.string.at_least_choice_one,
							Toast.LENGTH_LONG).show();
				}
				return;

			}

			// 若该选项只能单选
			if (multipleValueOnlyRadio(values[which])) {
				// 除此项外，其余值取消选择
				for (int i = 0; i < values.length; i++) {
					listView.setItemChecked(i, i == which);
					checkedItems[i] = (i == which);
				}

				// 若该选项能多选
			} else {

				for (int i = 0; i < values.length; i++) {
					// 其余单选项取消选择
					if (multipleValueOnlyRadio(values[i])) {
						listView.setItemChecked(i, false);
						checkedItems[i] = false;
					}
				}
			}
		}
	};

	/**
	 * 显示多选对话框
	 * 
	 * @param item
	 * @param listener
	 */
	private void showAlertMultipleChoiceDialog(ResultIntArrayPics item,
			DialogInterface.OnMultiChoiceClickListener listener) {
		ArrayList<Integer> ints = item.result;
		checkedItems = new boolean[values.length];
		for (int i : ints)
			checkedItems[i] = true;

		DialogInterface.OnClickListener okClickListener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				ResultIntArrayPics item = arrays[index];

				ArrayList<Integer> ints = new ArrayList<Integer>();
				for (int i = 0; i < checkedItems.length; i++) {
					if (checkedItems[i])
						ints.add(i);
				}
				item.result = ints;
				notifyDataSetChanged();

			}
		};
		new AlertDialog.Builder(mContext).setTitle(item.name)
				.setMultiChoiceItems(values, checkedItems, listener)
				.setPositiveButton(R.string.ok, okClickListener)
				.setNegativeButton(R.string.cancel, null).create().show();

	}

	private OnClickListener editPicListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (listener != null)
				listener.onPhotoEdit((ResultIntArrayPics) v.getTag());
		}

	};

	class ViewHolder {
		TextView titleTv;
		TextView valueTv;
//		ImageView markIv;
		LinearLayout photoContainer;
//		View gapView;
		FrameLayout photoFl;
		ImageView photoIv;
		BadgeView badge;
		ImageView photoAddIv;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder;
		if (convertView == null) {
			viewHolder = new ViewHolder();
			convertView = inflater.inflate(
					R.layout.item_condition_paint_surface, null);
			convertView.setTag(viewHolder);
			viewHolder.titleTv = (TextView) convertView
					.findViewById(R.id.subject_tv);
			viewHolder.valueTv = (TextView) convertView
					.findViewById(R.id.guise_result_tv);
//			viewHolder.markIv = (ImageView) convertView
//					.findViewById(R.id.mark_flag_iv);
			viewHolder.photoContainer = (LinearLayout) convertView
					.findViewById(R.id.exception_photo_container_ll);
			viewHolder.photoFl = (FrameLayout) convertView
					.findViewById(R.id.exception_photo_layout);
			viewHolder.photoIv = (ImageView) convertView
					.findViewById(R.id.exception_photo_iv);
			viewHolder.badge = new BadgeView(mContext);
			viewHolder.badge.setBackground(9,
					GlobalInfo.resources.getColor(R.color.deep_red));
			viewHolder.badge.setTargetView(viewHolder.photoFl);
			viewHolder.badge.setBadgeMargin(4);
			viewHolder.photoAddIv = (ImageView) convertView
					.findViewById(R.id.add_exception_photo_iv);
			 viewHolder.valueTv.setMinWidth(resultTvWidth);
			viewHolder.valueTv.setOnClickListener(resultListener);
			viewHolder.photoAddIv.setOnClickListener(photoAddListener);
			viewHolder.photoIv.setOnClickListener(editPicListener);

		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		ResultIntArrayPics item = arrays[position];
		viewHolder.photoAddIv.setTag(item);
		viewHolder.photoIv.setTag(item);

		boolean addIvVisible = !setResult(item, viewHolder.valueTv);
		viewHolder.photoAddIv.setVisibility(addIvVisible ? View.VISIBLE
				: View.INVISIBLE);
		if (item.pic_path_list.size() > 0) {
			viewHolder.photoFl.setVisibility(View.VISIBLE);
			Bitmap bitmap = Util.getimage(item.pic_path_list.get(0), 300, 300);
			if (bitmap == null)
				viewHolder.photoIv
						.setImageResource(R.mipmap.ic_launcher);
			else
				viewHolder.photoIv.setImageBitmap(bitmap);
		} else {
			viewHolder.photoFl.setVisibility(View.GONE);
		}
		viewHolder.badge.setBadgeCount(item.pic_path_list.size());

		viewHolder.titleTv.setText(item.name);
		viewHolder.valueTv.setTag(position);

		return convertView;
	}

	/**
	 * 只能单选的多选值
	 * 
	 * @param value
	 * @return
	 */
	private boolean multipleValueOnlyRadio(String value) {
		return "正常".equals(value) || "无".equals(value) || "丢失".equals(value);
	}

	/**
	 * 是否正常结果
	 * 
	 * @param value
	 * @return
	 */
	private boolean isRegularResult(String value) {
		return "正常".equals(value) || "无".equals(value);
	}

	/**
	 * 设置值
	 * 
	 * @param item
	 * @param tv
	 */
	private boolean setResult(ResultIntArrayPics item, TextView tv) {

		// 若为空值，默认为0
//		if (item.result.size() == 0)
//			item.result.add(0);

		String value = "";
		for (int i : item.result) {
			if (TextUtils.isEmpty(value))
				value = values[i];
			else
				value += " " + values[i];
		}
		tv.setText(value);

		if (item.result.size()<=0 || isRegularResult(values[item.result.get(0)])) {// 正常
			tv.setBackgroundResource(R.color.deep_green);
			tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_blue_yes,
					0, R.mipmap.ic_drop_arrow, 0);
			return true;
		} else {
			tv.setBackgroundResource(R.color.deep_red);
			tv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_red_cross,
					0, R.mipmap.ic_drop_arrow, 0);
			return false;
		}

	}

	class HeaderViewHolder {
		TextView title;
//		TextView mark;
	}

	public View getHeaderView(int position, View convertView, ViewGroup parent) {
		HeaderViewHolder viewHolder;
		if (convertView == null) {
			viewHolder = new HeaderViewHolder();
			convertView = inflater.inflate(
					R.layout.item_condition_paint_surface_subject, null);
			convertView.setTag(viewHolder);
			viewHolder.title = (TextView) convertView
					.findViewById(R.id.subject_tv);
//			viewHolder.mark = (TextView) convertView
//					.findViewById(R.id.subject_mark_tv);

		} else {
			viewHolder = (HeaderViewHolder) convertView.getTag();
		}
		ResultIntArrayPics item = arrays[position];
		viewHolder.title.setText(item.header);
		return convertView;
	}

	@Override
	public long getHeaderId(int position) {
		return arrays[position].header.hashCode();
	}
}
